<template>
  <!-- 添加或修改报销发票信息管理对话框 -->
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body v-dialogDrag width="80%">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form :model="form" :rules="rules" label-width="80px" ref="form">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>基本信息</span>
            </div>
            <el-col :span="24">
              <el-form-item label="申请日期" prop="imburseDate">
                <el-date-picker clearable
                                placeholder="请选择报销日期"
                                type="date"
                                v-model="form.imburseDate"
                                value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="报销金额" prop="imburseMoney">
                <el-input disabled placeholder="请输入报销金额" v-model="form.imburseMoney"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发放乙方" prop="remCompany" style="width: 210px">
                <el-select v-model="form.remCompany" placeholder="请选择乙方" clearable style="width: 210px">
                  <el-option v-for="dict in dict.type.company"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <template v-if="form.type == '0'">
              <!--<el-col :span="24">
                <el-form-item label="项目名称" prop="prjid">
                  <el-select v-model="form.prjid" placeholder="请选择项目" filterable clearable ref="prjselect">
                    &lt;!&ndash; style="width: 300px"&ndash;&gt;
                    <el-option v-for="dict in PrjNameOptions"
                               :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>-->
              <el-col :span="24">
                <el-form-item label="请款人" prop="qkrmc">
                  <el-select v-model="form.qkrmc" placeholder="请款人名称" filterable clearable ref="qkrmc"><!--style="width: 300px"-->
                    <el-option v-for="dict in SupplierNameOptions"
                               @click.native="changeSupp(dict)"
                               :key="dict.dictValue" :label="dict.id" :value="dict.dictLabel"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="24">
              <el-form-item label="请款事由" prop="qksy">
                <el-input placeholder="请输入请款事由" v-model="form.qksy"/><!-- @change="changeQksy"-->
              </el-form-item>
            </el-col>
            <template v-if="form.type == '0'">
              <el-col :span="24">
                <el-form-item label="资金用途" prop="zjyt">
                  <el-input placeholder="请输入资金用途(货款,运费 等)" v-model="form.zjyt"/>
                </el-form-item>
              </el-col>
              <!--<el-col :span="24">
                <el-form-item label="付款备注信息" prop="qkbz">
                  <el-input placeholder="请输入付款备注信息(不需备注请填“无”)" type="textarea" v-model="form.qkbz"/>
                </el-form-item>
              </el-col>-->
            </template>
            <!--<el-row :gutter="20" v-if="form.type == '1'">
              <el-col :span="24">
                <el-form-item label="请款事由" prop="qksy">
                  <el-input placeholder="请输入请款事由" v-model="form.qksy"/>&lt;!&ndash; @change="changeQksy"&ndash;&gt;
                </el-form-item>
              </el-col>
              &lt;!&ndash;<el-col :span="24">
                <el-form-item label="资金用途" prop="zjyt">
                  <el-input placeholder="请输入资金用途(货款,运费 等)" v-model="form.zjyt" @change="zcZjyt"/>
                </el-form-item>
              </el-col>&ndash;&gt;
              &lt;!&ndash;<el-col :span="24">
                <el-form-item label="请款合计" prop="qkhj">
                  <el-input placeholder="请输入请款合计" v-model="form.qkhj"/>
                </el-form-item>
              </el-col>&ndash;&gt;
            </el-row>-->
            <el-col :span="24">
              <el-form-item label="付款备注" prop="qkbz">
                <el-input placeholder="请输入付款备注(不需备注请填“无”)" type="textarea" v-model="form.qkbz"/>
                <!--@change="changeRemark"-->
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="其他备注">
                <el-input placeholder="请输入其他备注" type="textarea" v-model="form.infomation"/>
              </el-form-item>
            </el-col>
          </el-card>
        </el-form>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button @click="handleAddOrderList" icon="el-icon-plus" plain size="mini" type="primary">选择商品
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button @click="handleExport()" v-if="this.form.id" icon="el-icon-download" plain size="mini"
                           type="warning">导出
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-table :data="form.orderList" v-loading="loadingOrderList" :max-height="tableMaxHeight">
            <el-table-column align="center" label="商品名称" prop="name"/>
            <el-table-column align="center" label="商品品牌" prop="brand"/>
            <el-table-column align="center" label="商品型号" prop="model"/>
            <el-table-column align="center" label="商品单位" prop="unit"/>
            <!--      <el-table-column align="center" label="含税单价" prop="costPriceTax"/>-->
            <el-table-column align="center" label="采购数量" prop="count"/>
            <el-table-column align="center" label="采购单价" prop="costPrice"/>
            <el-table-column align="center" label="采购总价" prop="cost"/>
            <!--            <el-table-column align="center" label="库存数量" prop="remainderCount"/>-->
            <el-table-column align="center" label="采购人姓名" prop="buyName"/>
            <el-table-column label="采购日期" align="center" prop="buyDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.buyDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template slot-scope="scope">
                <el-popconfirm :title="`确认移除当前数据项？`" @confirm="handleDeleteRow(scope.row)"
                               style="margin-left: 10px;">
                  <el-button icon="el-icon-delete" size="mini" slot="reference" type="text"
                  >移除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <div class="dialog-footer" slot="footer">
      <el-button @click="submitForm" type="primary">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <goods-order-in-list-for-imbursement @ok="updateOrderList"
                                         ref="GoodsOrderInListForImbursement"></goods-order-in-list-for-imbursement>
  </el-dialog>
</template>

<script>
    import {addAction, getAction, getById, updateAction, deepClone, downloadFile} from '@/api/manage';
    import GoodsOrderInListForImbursement from "../../goodsOrderIn/GoodsOrderInListForImbursement";

    export default {
        name: "GoodsReimbursementFormForOrder",
        dicts: ['imburse_status', 'yes_no', 'company'],/*'buy_type', */
        components: {
            GoodsOrderInListForImbursement,
        },
        data() {
            return {
                // 遮罩层
                loading: true,
                loadingOrderList: false,
                activeName: "first",
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                    /*prjid: [
                        {required: true, message: "项目名称不能为空", trigger: "blur"}
                    ],*/
                    remCompany: [
                        {required: true, message: "请选择发放乙方", trigger: "blur"}
                    ],
                    qkrmc: [
                        {required: true, message: "请款人名称不能为空", trigger: "blur"}
                    ],
                    /*qkrkhh: [
                        {required: true, message: "请款人开户行不能为空", trigger: "blur"}
                    ],
                    qkrzh: [
                        {required: true, message: "请款人账号不能为空", trigger: "blur"}
                    ],*/
                    zjyt: [
                        {required: true, message: "资金用途不能为空", trigger: "blur"}
                    ],
                    qksy: [
                        {required: true, message: "请款事由不能为空", trigger: "blur"}
                    ],
                    qkbz: [
                        {required: true, message: "付款备注不能为空(不需备注请填“无”)", trigger: "blur"}
                    ],
                    /*qkhj: [
                        {required: true, message: "请款合计不能为空", trigger: "blur"}
                    ],*/
                },
                url: {
                    getById: '/goodsReimbursement/goodsReimbursement/',
                    add: '/goodsReimbursement/goodsReimbursement/add',
                    edit: '/goodsReimbursement/goodsReimbursement/edit',
                    addNew: '/goodsReimbursement/goodsReimbursement/addNew',
                    editNew: '/goodsReimbursement/goodsReimbursement/editNew',
                    // editOrderInfo: '/goodsOrderIn/goodsOrderIn/editForImburseId',
                    getSupplierById: '/goodsSupplier/goodsSupplier/',
                    digitUppercase: '/common/digitUppercase/',
                    // prjNames: '/projectBaseInfo/projectBaseInfo/prjNames',
                    suppNames: '/goodsSupplier/goodsSupplier/suppNames',
                },
                orderList: [],
                orderIds: "",
                // PrjNameOptions: [],
                SupplierNameOptions: [],
                newDate: "",
                tableMaxHeight: window.innerHeight - 320,
                queryParams: {},
                supplierId: "",
            };
        },
        computed: {
            visitedViews() {
                return this.$store.state.tagsView.visitedViews
            },
        },
        created() {
            // this.getCurrentMonth();
        },
        methods: {
            handleExport() {
                let that = this;
                that.loading = false;
                that.queryParams.imburseId = that.form.id;
                that.$confirm('是否确认导出报销明细表?', "确认", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    downloadFile('/goodsReimbursement/goodsReimbursement/export', that.queryParams);
                });
            },
            changeQksy(val) {
                let that = this;
                that.$set(that.form, "infomation", val);
            },
            //自采资金用途修改
            /*zcZjyt(val) {
                let that = this;
                // console.log(val);
                // console.log(that.form.zjyt);
                that.form.infomation = that.form.zjyt;
            },*/
            closeAllTags(view) {
                this.$tab.closeAllPage().then(({visitedViews}) => {
                    if (this.affixTags.some(tag => tag.path === this.$route.path)) {
                        return
                    }
                    // this.toLastView(visitedViews, view)
                })
            },
            getCurrentMonth() {
                let that = this;
                let Y = new Date().getFullYear();
                let M = new Date().getMonth() + 1;
                let M2 = new Date().getMonth();
                let D = new Date().getDate();
                // let times = Y + (M < 10 ? "-0" : "-") + M + (D < 10 ? "-0" : "-") + D;
                let times = Y + (M2 < 10 ? "年0" : "年") + M2 + "月";
                // that.form.infomation = times;
                // that.form.qkbz = times;
                // that.form.qksy = times;
                if (that.form.type == '0') {//公采
                    that.$set(that.form, "zjyt", "采购货款");
                    that.$set(that.form, "infomation", times + "公采打款");
                    that.$set(that.form, "qksy", times + "XX款项");
                } else {//自采
                    let nickName = that.$store.getters.nickName;
                    that.$set(that.form, "qksy", times + nickName + "自采款项");
                    that.$set(that.form, "infomation", times + that.$store.getters.nickName + "自采报销");
                    that.$set(that.form, "qkrmc", nickName);
                }
            },
            //选择请款人名称时,更新开户行和账号
            //TODO 需要验证开户行和账号是否为空,则进行提示
            changeSupp(dict) {
                let that = this;
                if (dict.label && dict.value) {
                    that.form.qkrkhh = dict.label;
                    that.form.qkrzh = dict.value;
                    that.supplierId = dict.dictValue;
                    let qksy = that.form.qksy;
                    qksy = qksy.replace("XX", dict.dictLabel)
                    that.$set(that.form, "qksy", qksy);
                } else {
                    that.$confirm('请款人(供应商)：“' + dict.dictLabel + '” 开户行或账号为空, 是否跳转至供应商管理维护数据?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {//跳转到供应商信息管理
                        that.closeAllTags(null);
                        that.$router.replace("/customerinfos/goodsSupplier");
                    }).catch(() => {//关闭页面并清空请款人信息
                        that.form.qkrmc = "";
                        that.supplierId = "";
                    });
                }
            },
            /*intDictsForPrj() {
                let that = this;
                getAction(that.url.prjNames, {orderByColumn: "create_time", isAsc: "desc"}).then(res => {
                    that.PrjNameOptions = res.data.nameList;
                })
            },*/
            intDictsForSupp() {
                let that = this;
                getAction(that.url.suppNames, {orderByColumn: "sort", isAsc: "asc", pageSizeZero: true,}).then(res => {
                    that.SupplierNameOptions = res.data.nameList;
                })
            },
            /* changeRemark(val1) {
                 let that = this;
                 that.form.infomation = that.form.qkbz;
                 // that.$set(that.form.qkbz, "infomation", val1);
             },*/
            //获取供应商信息
            getSupplierById(supplierId) {
                let that = this;
                getById(this.url.getSupplierById, supplierId).then(response => {
                    let data = response.data;
                    if (data.bankName && data.bankNo) {
                        that.$set(this.form, "qkrmc", data.name);
                        that.$set(this.form, "qkrkhh", data.bankName);
                        that.$set(this.form, "qkrzh", data.bankNo);
                    } else {
                        that.$confirm('请款人(供应商)：“' + data.name + '” 开户行或账号为空, 是否跳转至供应商管理维护数据?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {//跳转到供应商信息管理
                            that.closeAllTags(null);
                            that.$router.replace("/customerinfos/goodsSupplier");
                        }).catch(() => {//关闭页面并清空请款人信息
                            that.form.qkrmc = "";
                        });
                    }
                });
            },
            //金额转大写
            digitUppercase(num) {
                let that = this;
                getById(this.url.digitUppercase, num).then(response => {
                    that.$set(this.form, "qkhj", response.msg);
                });
            },
            //删除当前行,并解除入库商品绑定的报销信息id
            handleDeleteRow(row) {
                let that = this;
                let id = row.id;
                let orderIds = "";
                let selectRows = [];
                let imburseMoney = 0;
                that.form.orderList.forEach(selectRow => {
                    if (selectRow.id != id) {
                        orderIds += "," + selectRow.id;
                        selectRows.push(selectRow);
                        imburseMoney = imburseMoney + selectRow.cost
                    }
                })
                that.form.goodsIds = orderIds;
                that.form.orderList = selectRows;
                that.form.imburseMoney = imburseMoney;
                that.form.remRemain = imburseMoney;
                that.digitUppercase(imburseMoney);
                /*updateAction(that.url.editOrderInfo, {"id": row.id, "imburseId": ""}).then(response => {
                    that.orderList = that.orderList.filter((item) => {
                        return item.id != row.id
                    });
                    that.form.orderList = that.orderList;
                    updateAction(that.url.editNew, that.form).then(response => {
                        that.$modal.msgSuccess("更新成功!");
                    });
                });*/
            },
            //打开选择商品弹窗
            handleAddOrderList() {
                // this.$refs.GoodsOrderInListForImbursement.showSelectOrderList(this.form.type);
                // this.$refs.GoodsOrderInListForImbursement.showSelectOrderList0626(this.form.type, this.form.goodsIds);
                this.$refs.GoodsOrderInListForImbursement.showSelectOrderList1118(this.form.type, this.form.goodsIds, this.supplierId);
            },
            //选择商品成功后,将选择的商品放进当前页面的商品列表中
            updateOrderList(selectRows) {
                let that = this;
                if (that.form.type == '0') {
                    let continueFlag = true;
                    let orderIds = deepClone(that.form.goodsIds);
                    let orderList = deepClone(that.form.orderList);
                    let imburseMoney = deepClone(that.form.imburseMoney);
                    let supplierId = "";
                    // let qksy = that.form.qksy;//请款事由
                    for (let i = 0; i < selectRows.length; i++) {
                        let row = selectRows[i];
                        if (orderIds.indexOf(row.id) == -1) {
                            orderIds += "," + row.id;
                            orderList.push(row);
                            imburseMoney = imburseMoney + row.cost;
                            // if (qksy.indexOf(row.name) == -1) {
                            //     qksy = qksy + row.name + ";";
                            // }
                        }
                        if (supplierId == "" || supplierId == row.supplierId) {
                            supplierId = row.supplierId;
                        } else if (supplierId != row.supplierId) {//选择的商品供货商不一致,退出逻辑并提示重新选择商品
                            continueFlag = false;
                            that.$modal.msgError("商品供货商不一致,请重新选择");
                            orderIds = that.form.goodsIds;
                            orderList = that.form.orderList;
                            imburseMoney = that.form.imburseMoney;
                            break;
                        }
                    }
                    if (continueFlag) {
                        that.getSupplierById(supplierId);
                        that.digitUppercase(imburseMoney);
                        that.form.goodsIds = orderIds;
                        that.form.orderList = orderList;
                        that.form.imburseMoney = imburseMoney;
                        that.form.remRemain = imburseMoney;
                        // that.form.qksy = qksy;
                    }
                } else {
                    let orderIds = that.form.goodsIds;
                    let orderList = that.form.orderList;
                    let imburseMoney = that.form.imburseMoney;
                    for (let i = 0; i < selectRows.length; i++) {
                        let row = selectRows[i];
                        if (orderIds.indexOf(row.id) == -1) {
                            orderIds += "," + row.id;
                            orderList.push(row);
                            imburseMoney = imburseMoney + row.cost
                        }
                    }
                    that.form.goodsIds = orderIds;
                    that.form.orderList = orderList;
                    that.form.imburseMoney = imburseMoney;
                    that.form.remRemain = imburseMoney;
                    that.digitUppercase(imburseMoney);
                }
                /*let orderIds = that.form.goodsIds;
                let orderList = that.form.orderList;
                let imburseMoney = that.form.imburseMoney;
                for (let i = 0; i < selectRows.length; i++) {
                    let row = selectRows[i];
                    if (orderIds.indexOf(row.id) == -1) {
                        orderIds += "," + row.id;
                        orderList.push(row);
                        imburseMoney = imburseMoney + row.cost
                    }
                }
                that.form.goodsIds = orderIds;
                that.form.orderList = orderList;
                that.form.imburseMoney = imburseMoney;
                that.form.remRemain = imburseMoney;*/
                // that.submitFormNew();
            },
            /*submitFormNew() {
                let that = this;
                that.$refs["form"].validate(valid => {
                    if (valid) {
                        if (that.form.id != null) {
                            updateAction(that.url.editNew, that.form).then(response => {
                                that.$modal.msgSuccess("选择商品成功");
                            });
                        } else {
                            addAction(that.url.addNew, that.form).then(response => {
                                that.$modal.msgSuccess("选择商品成功");
                                that.form = response.data;
                            });
                        }
                    }
                });
            },*/

            //打开弹窗,用于显示关联的商品列表
            handleAddNewImbursement(type) {
                let that = this;
                that.reset();
                that.open = true;
                if (type == '0') {
                    that.title = "公采报销";
                    //获取项目选择项
                    // that.intDictsForPrj();
                    //获取供应商选择项
                    that.intDictsForSupp();
                } else {
                    that.title = "自采报销";
                }
                that.form.type = type;
                //获取请款事由月份并填充
                that.getCurrentMonth();
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    type: null,
                    userId: this.$store.getters.userId,
                    userName: this.$store.getters.nickName,
                    imburseDate: new Date(),
                    imburseMoney: null,
                    taxId: null,
                    taxNo: null,
                    taxMoney: null,
                    infomation: "",
                    goodsIds: "",
                    file: null,
                    status: "0",
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    remark: null,
                    orderList: [],
                    prjname: "",
                    qkrmc: "",
                    qkrkhh: "",
                    qkrzh: "",
                    zjyt: "",
                    qksy: "",
                    qkhj: "",
                    qkbz: "",
                    deptId: this.$store.getters.deptId,
                    deptName: this.$store.getters.deptName,
                };
                this.orderList = [];
                this.resetForm("form");
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加报销发票信息管理";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                let that = this;
                that.reset();
                const id = row.id || that.ids;
                getById(that.url.getById, id).then(response => {
                    that.form = response.data;
                    // that.orderList = that.form.orderList;
                    that.open = true;
                    that.title = "修改报销发票信息管理";
                });
            },
            /** 提交按钮 */
            submitForm() {
                let that = this;
                that.$refs["form"].validate(valid => {
                    if (valid) {
                        that.form.status = "0";
                        if (that.$refs.prjselect) {
                            that.form.prjname = that.$refs.prjselect.selected.label;
                        }
                        if (that.form.id != null) {
                            updateAction(that.url.editNew, that.form).then(response => {
                                that.$modal.msgSuccess("修改成功");
                                that.open = false;
                                that.$emit('ok');
                            });
                        } else {
                            addAction(that.url.addNew, that.form).then(response => {
                                that.$modal.msgSuccess("新增成功");
                                that.open = false;
                                that.$emit('ok');
                            });
                        }
                    }
                });
            },
        }
    };
</script>
